package cn.tedu._05weibo.controller;

import cn.tedu._05weibo.common.response.JsonResult;
import cn.tedu._05weibo.common.response.StatusCode;
import cn.tedu._05weibo.mapper.WeiboMapper;
import cn.tedu._05weibo.pojo.dto.WeiboDTO;
import cn.tedu._05weibo.pojo.entity.User;
import cn.tedu._05weibo.pojo.entity.Weibo;
import cn.tedu._05weibo.pojo.vo.WeiboDetailVO;
import cn.tedu._05weibo.pojo.vo.WeiboIndexVO;
import cn.tedu._05weibo.pojo.vo.userVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

@Api(tags = "02.微博模块")
@RestController
@RequestMapping("v1/weibo/")
public class WeiboController {

    @Autowired
    private WeiboMapper weiboMapper;

    //    1.发布微博功能
    @ApiOperation("发布微博功能")
    @PostMapping("insert")
    public JsonResult insert(@RequestBody WeiboDTO weiboDTO, @ApiIgnore HttpSession session) {
        System.out.println("weiboDTO = " + weiboDTO + ", session = " + session);

        userVO userVO = (userVO) session.getAttribute("user");
        if (userVO == null) {
            return new JsonResult(StatusCode.NOT_LOGIN);
        }

        Weibo weibo = new Weibo();
        BeanUtils.copyProperties(weiboDTO, weibo);
        weibo.setCreated(new Date());
//        设置用户的Id
        weibo.setUserId(userVO.getId());

        weiboMapper.insert(weibo);
        return JsonResult.ok();
    }

    //    2.微博首页显示
    @ApiOperation("微博首页功能")
    @GetMapping("selectIndex")
    public JsonResult selectIndex() {
        List<WeiboIndexVO> weiboIndexVOS = weiboMapper.selectIndex();
        return JsonResult.ok(weiboIndexVOS);
    }

//    3.微博详细页面
    /*
     * @ApiImplicitParam 接收的默认属性值为 String
     * */

    @ApiOperation("微博详细页面功能")
    @ApiImplicitParam(name = "id", value = "微博ID", required = true, dataType = "Long")
    @GetMapping("selectById")
    public JsonResult selectById(
            @Range(min = 200,max = 300,message = "微博Id的范围不正确,请输入200-300之间的数值")
            @RequestParam("id") Long id) {
//        手动抛出异常
        if (id <0){
            throw  new IllegalArgumentException("ID的值小于0");

        }

        return JsonResult.ok(weiboMapper.selectById(id));
    }
}
